#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
   

    int fd_c = socket(PF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(-1, fd_c, "socket");

    char buf[1024] = {0};
    struct sockaddr_in addr_s;

    addr_s.sin_family = PF_INET;
    addr_s.sin_port = htons(atoi(argv[2]));

    addr_s.sin_addr.s_addr = inet_addr(argv[1]);
    // 发起连接请求

    int ret = connect(fd_c, (void *)&addr_s, sizeof addr_s);
    ERROR_CHECK(-1, ret, "connect");
    puts("connect success!");

    while (1)
    {
        printf("<<");
        fgets(buf, 1024, stdin);
        write(fd_c, buf, 1024);
        if (0 == strncasecmp(buf, "quit", 4))
        {
            break;
        }
        memset(buf, 0, 1024);
        int ret = read(fd_c, buf, 1024);
        if (NULL != strstr(buf, "开始下载>"))
        {
           
            char *filename = &buf[13];
            int fd_dest = open(filename,O_CREAT|O_TRUNC|O_RDWR,0664);
            int dn_ret = 0;
            while (dn_ret = read(fd_c,buf,sizeof(buf)))
            {
                write(fd_dest,buf,dn_ret);
                // if (strncmp(buf,"end",3))
                // {
                //    break;
                // }
                
                
            }   
        }
        if (ret != 0)
        {
           printf("net:%s\n", buf);
        }
        
       
    }
    close(fd_c);
    return 0;
}
